from fastapi import APIRouter
from service.ChatTTS_service import ChatTTSService
from entity.schema.ChatTTS_schema import ChatTTSRequest, ChatTTSResponse, BaseResponse, ErrorResponse
from models.ChatTTS_model import AudioFileListResponse

router = APIRouter()
chat_tts_service = ChatTTSService()

@router.post("/chat_tts", response_model=BaseResponse, responses={500: {"model": ErrorResponse}})
async def chat_text_to_speech(request: ChatTTSRequest):
    try:
        audio_file = chat_tts_service.generate_speech(request)
        return BaseResponse(
            code=200,
            msg="语音生成成功",
            data=ChatTTSResponse(
                status="success",
                filename=audio_file.filename,
                url=f"/chat_audio/{audio_file.filename}",
                text=audio_file.text,
                length=audio_file.file_size
            )
        )
    except Exception as e:
        return ErrorResponse(code=500, msg=str(e))

# 新增获取音频文件列表接口
@router.get("/chat_tts/files", response_model=BaseResponse, responses={500: {"model": ErrorResponse}})
async def get_chat_tts_files():
    try:
        audio_files = chat_tts_service.get_audio_files()
        return BaseResponse(
            code=200,
            msg="获取文件列表成功",
            data=audio_files
        )
    except Exception as e:
        return ErrorResponse(code=500, msg=str(e))

# 新增清理旧文件接口
@router.post("/chat_tts/clean_old_files", response_model=BaseResponse, responses={500: {"model": ErrorResponse}})
async def clean_chat_tts_old_files():
    try:
        deleted_count = chat_tts_service.clean_old_audio_files()
        return BaseResponse(
            code=200,
            msg=f"成功清理 {deleted_count} 个旧文件",
            data=None
        )
    except Exception as e:
        return ErrorResponse(code=500, msg=str(e))